<template>
  <div class="search-filter-container">
    <div class="search-section">
      <div class="search-input-group">
        <input
          v-model="searchQuery"
          type="text"
          placeholder="搜索成员姓名..."
          class="search-input"
          @input="handleSearch"
        />
        <button @click="clearSearch" class="clear-btn" v-if="searchQuery">
          ✕
        </button>
      </div>
    </div>

    <div class="filter-section">
      <div class="filter-group">
        <label class="filter-label">性别:</label>
        <div class="filter-options">
          <label class="filter-option">
            <input
              type="checkbox"
              v-model="filters.gender"
              value="男"
              @change="handleFilter"
            />
            <span class="option-text">男</span>
          </label>
          <label class="filter-option">
            <input
              type="checkbox"
              v-model="filters.gender"
              value="女"
              @change="handleFilter"
            />
            <span class="option-text">女</span>
          </label>
        </div>
      </div>

      <div class="filter-group">
        <label class="filter-label">世代:</label>
        <div class="filter-options">
          <label 
            v-for="gen in availableGenerations" 
            :key="gen"
            class="filter-option"
          >
            <input
              type="checkbox"
              v-model="filters.generations"
              :value="gen"
              @change="handleFilter"
            />
            <span class="option-text">第{{ gen }}代</span>
          </label>
        </div>
      </div>

      <div class="filter-group">
        <label class="filter-label">状态:</label>
        <div class="filter-options">
          <label class="filter-option">
            <input
              type="checkbox"
              v-model="filters.isAlive"
              :value="true"
              @change="handleFilter"
            />
            <span class="option-text">在世</span>
          </label>
          <label class="filter-option">
            <input
              type="checkbox"
              v-model="filters.isAlive"
              :value="false"
              @change="handleFilter"
            />
            <span class="option-text">已故</span>
          </label>
        </div>
      </div>

      <div class="filter-group">
        <label class="filter-label">年龄范围:</label>
        <div class="age-range">
          <input
            v-model.number="filters.minAge"
            type="number"
            placeholder="最小年龄"
            class="age-input"
            @input="handleFilter"
          />
          <span class="age-separator">-</span>
          <input
            v-model.number="filters.maxAge"
            type="number"
            placeholder="最大年龄"
            class="age-input"
            @input="handleFilter"
          />
        </div>
      </div>
    </div>

    <div class="filter-actions">
      <button @click="clearAllFilters" class="btn btn-secondary">
        清除筛选
      </button>
      <button @click="exportFiltered" class="btn btn-primary">
        导出结果
      </button>
    </div>

    <div class="filter-summary" v-if="hasActiveFilters">
      <span class="summary-text">
        筛选结果: {{ filteredCount }} 个成员
      </span>
    </div>
  </div>
</template>

<script>
import { ref, computed, watch } from 'vue';

export default {
  name: 'SearchFilter',
  props: {
    members: {
      type: Array,
      default: () => []
    }
  },
  emits: ['filter-change'],
  setup(props, { emit }) {
    const searchQuery = ref('');
    const filters = ref({
      gender: [],
      generations: [],
      isAlive: [],
      minAge: null,
      maxAge: null
    });

    // 计算可用的世代
    const availableGenerations = computed(() => {
      const generations = [...new Set(props.members.map(m => m.generation))];
      return generations.sort((a, b) => a - b);
    });

    // 计算筛选后的成员
    const filteredMembers = computed(() => {
      let result = [...props.members];

      // 搜索过滤
      if (searchQuery.value.trim()) {
        const query = searchQuery.value.toLowerCase();
        result = result.filter(member => 
          member.name.toLowerCase().includes(query) ||
          (member.description && member.description.toLowerCase().includes(query))
        );
      }

      // 性别过滤
      if (filters.value.gender.length > 0) {
        result = result.filter(member => 
          filters.value.gender.includes(member.gender)
        );
      }

      // 世代过滤
      if (filters.value.generations.length > 0) {
        result = result.filter(member => 
          filters.value.generations.includes(member.generation)
        );
      }

      // 状态过滤
      if (filters.value.isAlive.length > 0) {
        result = result.filter(member => 
          filters.value.isAlive.includes(member.isAlive)
        );
      }

      // 年龄过滤
      if (filters.value.minAge !== null || filters.value.maxAge !== null) {
        result = result.filter(member => {
          if (!member.birthDate) return false;
          
          const birthYear = new Date(member.birthDate).getFullYear();
          const currentYear = new Date().getFullYear();
          const age = currentYear - birthYear;

          if (filters.value.minAge !== null && age < filters.value.minAge) {
            return false;
          }
          if (filters.value.maxAge !== null && age > filters.value.maxAge) {
            return false;
          }
          return true;
        });
      }

      return result;
    });

    // 是否有活跃的筛选条件
    const hasActiveFilters = computed(() => {
      return searchQuery.value.trim() ||
             filters.value.gender.length > 0 ||
             filters.value.generations.length > 0 ||
             filters.value.isAlive.length > 0 ||
             filters.value.minAge !== null ||
             filters.value.maxAge !== null;
    });

    // 筛选结果数量
    const filteredCount = computed(() => filteredMembers.value.length);

    // 处理搜索
    const handleSearch = () => {
      emitFilterChange();
    };

    // 处理筛选
    const handleFilter = () => {
      emitFilterChange();
    };

    // 清除搜索
    const clearSearch = () => {
      searchQuery.value = '';
      emitFilterChange();
    };

    // 清除所有筛选
    const clearAllFilters = () => {
      searchQuery.value = '';
      filters.value = {
        gender: [],
        generations: [],
        isAlive: [],
        minAge: null,
        maxAge: null
      };
      emitFilterChange();
    };

    // 导出筛选结果
    const exportFiltered = () => {
      const data = filteredMembers.value.map(member => ({
        姓名: member.name,
        性别: member.gender,
        出生日期: member.birthDate,
        世代: member.generation,
        状态: member.isAlive ? '在世' : '已故',
        描述: member.description || ''
      }));

      const csv = [
        Object.keys(data[0]).join(','),
        ...data.map(row => Object.values(row).join(','))
      ].join('\n');

      const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = `家族成员_${new Date().toISOString().split('T')[0]}.csv`;
      link.click();
    };

    // 发送筛选变化事件
    const emitFilterChange = () => {
      emit('filter-change', {
        filteredMembers: filteredMembers.value,
        filters: filters.value,
        searchQuery: searchQuery.value
      });
    };

    // 监听成员变化，重新计算筛选结果
    watch(() => props.members, () => {
      emitFilterChange();
    }, { deep: true });

    return {
      searchQuery,
      filters,
      availableGenerations,
      filteredMembers,
      hasActiveFilters,
      filteredCount,
      handleSearch,
      handleFilter,
      clearSearch,
      clearAllFilters,
      exportFiltered
    };
  }
};
</script>

<style scoped>
.search-filter-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.search-section {
  margin-bottom: 20px;
}

.search-input-group {
  position: relative;
  display: flex;
  align-items: center;
}

.search-input {
  flex: 1;
  padding: 10px 40px 10px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.2s;
}

.search-input:focus {
  border-color: #007bff;
}

.clear-btn {
  position: absolute;
  right: 8px;
  background: none;
  border: none;
  color: #999;
  cursor: pointer;
  padding: 4px;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.clear-btn:hover {
  background-color: #f0f0f0;
  color: #666;
}

.filter-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.filter-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.filter-label {
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.filter-option {
  display: flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
}

.filter-option input[type="checkbox"] {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.option-text {
  font-size: 13px;
  color: #555;
}

.age-range {
  display: flex;
  align-items: center;
  gap: 8px;
}

.age-input {
  flex: 1;
  padding: 6px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 13px;
  outline: none;
}

.age-input:focus {
  border-color: #007bff;
}

.age-separator {
  color: #666;
  font-weight: 500;
}

.filter-actions {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  font-weight: 500;
  transition: all 0.2s;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn-primary:hover {
  background-color: #0056b3;
}

.btn-secondary {
  background-color: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background-color: #545b62;
}

.filter-summary {
  padding: 10px;
  background-color: #e9ecef;
  border-radius: 4px;
  text-align: center;
}

.summary-text {
  font-size: 13px;
  color: #495057;
  font-weight: 500;
}

@media (max-width: 768px) {
  .filter-section {
    grid-template-columns: 1fr;
  }
  
  .filter-actions {
    flex-direction: column;
  }
  
  .age-range {
    flex-direction: column;
    gap: 4px;
  }
}
</style> 